package com.ajie.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ajie.config.annotation.RestControllerMapping;
import com.ajie.entity.BaseEntity;
import com.ajie.entity.FoodType;
import com.ajie.entity.Motion;
import com.ajie.entity.SysUser;
import com.ajie.entity.dto.MiniLogin;
import com.ajie.entity.enums.ErrorMsg;
import com.ajie.entity.properties.MiniProperties;
import com.ajie.model.PageParams;
import com.ajie.model.Result;
import com.ajie.service.FoodTypeService;
import com.ajie.service.MiniHttpService;
import com.ajie.service.MotionService;
import com.ajie.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: ajie
 * @createTime: 2024-08-17 14:21
 */
@Tag(name = "小程序相关接口")
@RestControllerMapping("mini")
public class MiniController {

    @Resource
    private MiniProperties properties;
    @Resource
    private MiniHttpService httpService;
    @Resource
    private SysUserService userService;
    @Resource
    private FoodTypeService foodTypeService;
    @Resource
    private MotionService motionService;

    @SaIgnore
    @Operation(summary = "小程序登陆", parameters = {
            @Parameter(name = "code", description = "小程序wx.login得到的code", required = true)
    })
    @GetMapping("login/{code}")
    public Result<Map<String, String>> login(@PathVariable String code) {
        String login = httpService.login(properties.getAppid(), properties.getSecret(), code);
        MiniLogin miniLogin = JSONUtil.parseObj(login).toBean(MiniLogin.class);
        if (miniLogin.getErrcode() != null) {
            return ErrorMsg.getResult(miniLogin.getErrcode());
        }
        SysUser user = userService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getOpenid, miniLogin.getOpenid()));
        if (user == null) {
            user = new SysUser();
            user.setOpenid(miniLogin.getOpenid());
            userService.save(user);
        }
        StpUtil.login(user.getId(), "mini");
        Map<String, String> map = new HashMap<>();
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        map.put("tokenHead", tokenInfo.tokenName);
        map.put("token", tokenInfo.tokenValue);
        return Result.success(map);
    }

    @SaIgnore
    @GetMapping("foodType/list")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "小程序查询分类")
    public Result<List<FoodType>> list() {
        LambdaQueryWrapper<FoodType> lqw = new LambdaQueryWrapper<>();
        lqw.select(FoodType::getTitle, FoodType::getId, FoodType::getIcon);
        return Result.success(foodTypeService.list(lqw));
    }

    @SaIgnore
    @PostMapping("index/list")
    @ApiOperationSupport(order = 3)
    @Operation(summary = "小程序运动资讯查询")
    public Result<Page<Motion>> homeList(@RequestBody PageParams<Motion> pageParams) {
        Motion params = pageParams.getParams();
        LambdaQueryWrapper<Motion> lqw = new LambdaQueryWrapper<>();
        lqw.select(Motion::getApplicableAge, Motion::getBeneficialPosition, Motion::getName, BaseEntity::getId);
        lqw.eq(params.getType() != null, Motion::getType, params.getType());
        lqw.and(l -> l.like(params.getName() != null, Motion::getName, params.getName()).or()
                .like(params.getBeneficialPosition() != null, Motion::getBeneficialPosition, params.getBeneficialPosition()));
        lqw.eq(Motion::getStatus, 1);
        lqw.orderByDesc(Motion::getPushTime);
        return Result.success(motionService.page(pageParams.getPage(), lqw));
    }

    @SaIgnore
    @GetMapping("index/info/{id}")
    @ApiOperationSupport(order = 3)
    @Operation(summary = "小程序运动资讯详情查询")
    public Result<Motion> getIndexInfo(@PathVariable String id) {
        return Result.success(motionService.getById(id));
    }

}
